package influx

import (
	influx "github.com/influxdata/influxdb/client/v2"
	"log"
	"time"
)

var (
	InfluxClient influx.Client = nil
	points       []*influx.Point
	lengthMax    = 500
)

type Influx struct {
	Client    influx.Client
	Database  string
	TagVal    map[string]string
	FieadsVal map[string]interface{}
}

func (ord *Influx) WriteToInfluxDB(ic influx.Client) error {
	bp, err := influx.NewBatchPoints(influx.BatchPointsConfig{
		Database: "cwi",
	})
	if err != nil {
		log.Println("batchPoints create error:", err.Error())
		return err
	}
	tags := make(map[string]string)
	if ord.TagVal != nil {
		for k, v := range ord.TagVal {
			tags[k] = v
		}
	}
	fields := make(map[string]interface{})
	if ord.FieadsVal != nil {
		for k, v := range ord.FieadsVal {
			fields[k] = v
		}
	}

	pt, err := influx.NewPoint("shortmsg", tags, fields, time.Now())

	if err != nil {
		log.Println("point create error:", err.Error())
		return err
	}
	if len(points) == lengthMax {
		bp.AddPoints(points)
		points = make([]*influx.Point, 0)
		points = append(points, pt)
		err = ic.Write(bp)
		if err != nil {
			log.Println("Influxdb insert error:", err.Error())
		}
		return err
	}
	points = append(points, pt)
	return nil
}
